package org.wenhuayuan.project.common.tab;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

/**
 * 单个fragment页面
 */
public class HiFragmentTabView extends FrameLayout {
    private HiTabViewAdapter viewAdapter;
    private int curPos;
    public HiFragmentTabView(@NonNull Context context) {
        this(context, null);
    }

    public HiFragmentTabView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HiFragmentTabView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.init();
    }

    private void init() {

    }

    public void setViewAdapter(HiTabViewAdapter viewAdapter) {
        if (null == viewAdapter || this.viewAdapter != null) return;
        this.viewAdapter = viewAdapter;
        this.curPos = -1; // 初始化-1，默认不选中任何
    }

    public HiTabViewAdapter getViewAdapter() {
        return viewAdapter;
    }

    public void setCurrentItem(int position) {
        if (null == viewAdapter) return;
        if (position < 0 || position > viewAdapter.getCount()-1) return;
        if (position != this.curPos) {
            this.curPos = position;
            viewAdapter.instantiateItem(this, position);
        }
    }
    /**
     * 获取当前fragment对应position
     * @return
     */
    public int getCurrentPos() {
        return this.curPos;
    }

    /**
     * 获取当前fragment
     * @return
     */
    public Fragment getCurrentFragment() {
        if(null == viewAdapter) {
            throw new IllegalArgumentException("err-getCurrentFragment:please call setAdapter first.");
        }

        return viewAdapter.getCurFragment();
    }
}
